package com.limit.aop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.ehcache.CacheKit;
import com.limit.constant.Constant;
import com.limit.model.Actor;
import com.limit.model.ActorModule;
import com.limit.model.Module;
import com.limit.utils.StringUtil;

public class AdminPerimissionAop implements Interceptor {

	@Override
	public void intercept(ActionInvocation ai) {
		Controller c = ai.getController();
		String username = StringUtil.valueOf(c.getSessionAttr(Constant.UserName));
		String actorId = StringUtil.valueOf(c.getSessionAttr(Constant.ActorId));
		if(null==username || null==actorId){
			c.removeSessionAttr(Constant.ActorId);
			c.removeSessionAttr(Constant.UserName);
			c.redirect("/login/index");
		}else{
			String permissionUrl = StringUtil.parseURL(c.getRequest().getServletPath());
			List<Map<String,Object>> userPermissionList = this.getPermissionList(Integer.valueOf(actorId),username);
			System.out.println("--------AOP----------");
//			System.out.println(userPermissionList);
			System.out.println(permissionUrl);
			if(null!=userPermissionList && userPermissionList.size()>0){
				for(Map<String,Object> map : userPermissionList){
					String moduleUrl = String.valueOf(map.get("url"));
					if(permissionUrl.equals(moduleUrl)){
						ai.invoke();
						//验证权限成功之后执行
						
						//设置basePath
						c.setAttr("basePath", c.getRequest().getContextPath());
						return;
					}
				}
			}
			c.redirect("/admin/nopermission");
		}
	}
	
	/**
	 * 获取登录用户的权限列表
	 */
	private List<Map<String,Object>> getPermissionList(int actorId,String username){
		List<Map<String,Object>> upl = CacheKit.get(Constant.CacheActorPermission, username);
		if(null==upl){
			upl = new ArrayList<Map<String,Object>>(); 
			Actor actor = Actor.dao.findById(actorId);
			List<ActorModule> umlist = actor.getAdminModuleList();
			if(null!=umlist && umlist.size()>0){
				for(ActorModule um : umlist){
					Map<String,Object> map = new HashMap<String,Object>();
					Module m = um.getModule();
					map.put("id",m.get("id"));
					map.put("pid", m.get("pid"));
					map.put("url", m.get("url"));
					map.put("name", m.get("menu_name"));
					upl.add(map);
				}
				CacheKit.put(Constant.CacheActorPermission, username, upl);
			}
		}
		return upl;
	}

}
